package com.he.security;

import com.alibaba.fastjson2.JSON;
import com.he.utils.AuthExceptionUtil;
import com.he.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author He
 * @version 1.0
 * @Date 2023/9/6 18:02
 * @Desc AuthenticationEntryPoint用于处理认证异常。当用户尝试访问受保护的资源，但尚未通过身份验证时，或者身份验证失败时
 *       根据异常类型判定返回的信息：
 *          * InsufficientAuthenticationException 未登录
 *          * InternalAuthenticationServiceException 用户不存在
 *          * BadCredentialsException //密码错误
 *          ......等等
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//        authException.printStackTrace();
        WebUtils.renderString(response, JSON.toJSONString(AuthExceptionUtil.getAuthExceptionType(authException)));
    }
}
